package linkedlist.test23;

import listbyorder.utils.ListNode;

/**
 *  合并K个排序链表
 * @author code_yc
 * @version 1.0
 * @date 2020/7/14 13:47
 */
public class Solution1 {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        return bs(lists, 0, lists.length - 1);
    }

    private ListNode bs(ListNode[] lists, int l, int r) {
        if (l == r) return lists[l];
        int mid = (l + r) >> 1;
        ListNode left = bs(lists, l, mid);
        ListNode right = bs(lists, mid + 1, r);
        // 合并两个链表
        return mergeTwoLists(left, right);
    }

    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode t = dummy;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                t.next = l2;
                l2 = l2.next;
            } else if (l2 == null) {
                t.next = l1;
                l1 = l1.next;
            } else {
                if (l1.val <= l2.val) {
                    t.next = l1;
                    l1 = l1.next;
                } else {
                    t.next = l2;
                    l2 = l2.next;
                }
            }
            t = t.next;
        }
        return dummy.next;
    }
}
